<?php

namespace app\api\controller;

class Workstation extends \app\common\controller\Api
{
    protected $noNeedLogin = 'index';
    protected $noNeedRight = '*';
    //工作站列表
    public function index(){
//        $list=\app\common\model\Workstation::where(['status'=>1])->field('* ,
//        (2 * 6378.137 * ASIN(	SQRT(POW( SIN( PI( ) * ( " . 用户$longitude . "- lng ) / 360 ), 2 ) + COS( PI( ) * " . 用户$latitude . " / 180 ) * COS(  lat * PI( ) / 180 ) * POW( SIN( PI( ) * ( " . 用户$latitude . "- lat ) / 360 ), 2 )))) AS distance')->select();
        $lat=$this->request->get('lat');
        $lng=$this->request->get('lng');
        $query=\app\common\model\Workstation::where(['status'=>1]);
        if($search=$this->request->get('search')){
            $query->where(function ($query) use ($search){
                $query->where('name','like',"%$search%")
                    ->whereOr('contact','like',"%{$search}%")
                    ->whereOr('tel','like',"%{$search}%")
                    ->whereOr('city','like',"%{$search}%")
                    ->whereOr('address','like',"%{$search}%");
            });

        }
        if($lat&&$lng){
            $list= $query->field("* , (6378.138 * 2 * asin(sqrt(pow(sin((lat * pi() / 180 - ".$lat." * pi() / 180) / 2),2) + cos(lat * pi() / 180) * cos(".$lat." * pi() / 180) * pow(sin((lng * pi() / 180 - ".$lng." * pi() / 180) / 2),2))) * 1000) as distance")
                ->order('distance')
                ->paginate();
        }else{
            $list= $query->order('id','desc')->paginate();
        }

//        $list=\app\common\model\Workstation::where(['status'=>1])->field("* , (2 * 6378.137 * ASIN(	SQRT(POW( SIN( PI( ) * ( " .$lng . "- lng ) / 360 ), 2 ) + COS( PI( ) * " . $lat . " / 180 ) * COS(  lat * PI( ) / 180 ) * POW( SIN( PI( ) * ( " . $lat . "- lat ) / 360 ), 2 )))) as distance")->paginate();

        $this->success('工作列表',$list);
    }
    //申请工作站
    public function save(){
        $params = $this->request->post();
        // 表单验证
        $this->shoproValidate($params, get_class(), 'save');
        $user=$this->auth->getUserinfo();
        $workstation=\app\common\model\Workstation::create([
            'name'=>$params['name'],
            'contact'=>$params['contact'],
            'tel'=>$params['tel'],
            'province_id'=>$params['province_id'],
            'city_id'=>$params['city_id'],
            'area_id'=>$params['area_id'],
            'city'=>$params['city'],
            'address'=>$params['address'],
            'lng'=>$params['lng'],
            'lat'=>$params['lat'],
            'user_id'=>$user['id'],
        ]);
        $this->success('提交成功',$workstation);
    }
}